package com.flyco.modules.oms.service.impl;

import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.JSONArray;
import com.alibaba.fastjson.JSONObject;
import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.flyco.common.constant.YunDaStatus;
import com.flyco.common.util.HttpUtil;
import com.flyco.common.util.oConvertUtils;
import com.flyco.modules.oms.entity.OmsOrderTrace;
import com.flyco.modules.oms.handle.ISyncLogisticsHandle;
import com.flyco.modules.oms.mapper.OmsOrderTraceMapper;
import com.flyco.modules.oms.model.OmsOrderYunDaTraceModel;
import com.flyco.modules.oms.service.IOmsOrderTraceService;
import com.flyco.modules.thread.ExecutorProcessPool;
import com.flyco.modules.util.ApiUtil;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;

import com.flyco.common.constant.ApiConstant;
import org.springframework.util.CollectionUtils;

import java.util.*;
import java.util.stream.Collectors;
import java.util.stream.Stream;

/**
 * @Description: 订单跟踪
 * @Author: flyco
 * @Date: 2020-03-25
 * @Version: V1.0
 */
@Slf4j
@Service
public class OmsOrderTraceServiceImpl extends ServiceImpl<OmsOrderTraceMapper, OmsOrderTrace> implements IOmsOrderTraceService {

    @Autowired
    private OmsOrderTraceMapper omsOrderTraceMapper;

    @Autowired
    private Map<String, ISyncLogisticsHandle> map;


    @Override
    public void syncLogistics() {
        List<String> list = omsOrderTraceMapper.getDeliverySnFromOrder();
        if (!CollectionUtils.isEmpty(list)) {
            //List<String> yunDaList = list.stream().filter(s->s.contains("韵达")).collect(Collectors.toList());
            //List<String> ztoList = list.stream().filter(s->s.contains("中通")).collect(Collectors.toList());
            ExecutorProcessPool pool = ExecutorProcessPool.getInstance();
            for (String item : list) {
                if (oConvertUtils.isNotEmpty(item) && item.contains("-")){
                    String[] str = item.split("-");
                    pool.execute(new ExcuteTask(str[0],str[1],str[2]));
                }
            }
        }

        //关闭线程池，如果是需要长期运行的线程池，不用调用该方法。
        //监听程序退出的时候最好执行一下。
        //pool.shutdown();
    }

    /**
     * 执行任务，实现Runable方式
     */
    class ExcuteTask implements Runnable {
        private String id;
        private String code;
        private String company;
        public ExcuteTask(String id, String code, String company) {
            this.code = code;
            this.id = id;
            this.company = company;
        }
        @Override
        public void run() {
            try {
                map.get("logisticsHandle-" + getCompanyKey(this.company)).syncLogistics(code, id);
//
//                if (company.contains("韵达")) {
//                    ISyncLogisticsHandle yunda = map.get("logisticsHandle-韵达");
//                    yunda.syncLogistics(code, id);
//                } else if (company.contains("中通")) {
//                    ISyncLogisticsHandle zto = map.get("logisticsHandle-中通");
//                    zto.syncLogistics(code, id);
//                }
            } catch (Exception e) {
                e.printStackTrace();
            }
            //System.out.println("-------------这里执行业务逻辑，Runnable TaskName = " + taskName + "-------------");
        }
        String getCompanyKey(String company){
            return Stream.of("韵达","中通","顺丰").filter(s->company.contains(s)).findAny().get();
        }
    }

    @Override
    public void syncLogisticsByCode(String code) {

    }

    /*private void syncFromYunDa(String billcode) {
        syncFromYunDa(billcode,null);
    }

    private void syncFromYunDa(String billcode, String orderId) {
        log.info("开始同步韵达物流单号 :" + billcode);
        StringBuilder url = new StringBuilder();
        url.append(ApiUtil.getYundaUrl());
        url.append("query/json.php?partnerid=feikewuliu&mailno=");
        url.append(billcode);
        log.info("url:" + url.toString());
        String result = HttpUtil.getRequest(url.toString());
        *//*String result = HttpUtil.createGet(url.toString())
                .contentType("application/json")
                .execute()
                .body();*//*

        if (! oConvertUtils.isEmpty(result)) {
            JSONObject resultObj = JSON.parseObject(result);
            String status = resultObj.getString("status");
            JSONArray jsonArray = resultObj.getJSONArray("steps");
            log.info("jsonArray:" + jsonArray);
            if (null != jsonArray && jsonArray.size() > 0) {
                List<OmsOrderYunDaTraceModel> addModels = new ArrayList<>();
                Integer dbCount = queryTraceList(billcode);
                List<OmsOrderYunDaTraceModel> models = jsonArray.toJavaList(OmsOrderYunDaTraceModel.class);
                Collections.sort(models, Comparator.comparing(OmsOrderYunDaTraceModel::getCreateTime));
                if (jsonArray.size() > dbCount) {
                    addModels = models.subList(dbCount, models.size());
                }
                //log.info("addModels:" + addModels);
                List<OmsOrderTrace> traces = new ArrayList<>();
                for (OmsOrderYunDaTraceModel traceModel : addModels) {
                    OmsOrderTrace trace = new OmsOrderTrace();
                    BeanUtils.copyProperties(traceModel, trace);
                    trace.setTraceNo(billcode);
                    trace.setLabel(YunDaStatus.fromName(traceModel.getLabel()).getStatusValue());
                    traces.add(trace);
                }
                //log.info("traces:" + traces);
                if (!CollectionUtils.isEmpty(traces)) {
                    this.saveBatch(traces);
                }

                if("signed".equalsIgnoreCase(status)) {
                    // TODO: 2020/4/8 处理订单签收
                    OmsOrderYunDaTraceModel traceModel =  models.get(models.size() - 1);
                    omsOrderTraceMapper.updateOrderSigned(orderId, billcode, traceModel.getCreateTime());
                }
            }
        }
    }


    private void syncFromOms(String billcode) {
        log.info("开始同步物流单号 :" + billcode);
        StringBuilder url = new StringBuilder();
        url.append(ApiUtil.getOmsUrl());
        url.append("server/api/YundaQuery/getQuery?billcode=");
        url.append(billcode);
        log.info("url:" + url.toString());
        String result = HttpUtil.getRequest(url.toString());
        *//*String result = HttpUtil.createGet(url.toString())
                .contentType("application/json")
                .execute()
                .body();*//*

        if (! oConvertUtils.isEmpty(result)) {
            JSONObject resultObj = JSON.parseObject(result);
            JSONArray jsonArray = resultObj.getJSONObject("data").getJSONObject(billcode).getJSONArray("route");
            log.info("jsonArray:" + jsonArray);
            if (null != jsonArray && jsonArray.size() > 0) {
                List<OmsOrderYunDaTraceModel> addModels = new ArrayList<>();
                Integer dbCount = queryTraceList(billcode);
                if (jsonArray.size() > dbCount) {
                    List<OmsOrderYunDaTraceModel> models = jsonArray.toJavaList(OmsOrderYunDaTraceModel.class);
                    Collections.sort(models, Comparator.comparing(OmsOrderYunDaTraceModel::getCreateTime));
                    addModels = models.subList(dbCount, models.size());
                }
                //log.info("addModels:" + addModels);
                List<OmsOrderTrace> traces = new ArrayList<>();
                for (OmsOrderYunDaTraceModel traceModel : addModels) {
                    OmsOrderTrace trace = new OmsOrderTrace();
                    BeanUtils.copyProperties(traceModel, trace);
                    trace.setTraceNo(billcode);
                    trace.setLabel(ApiConstant.TRACE_LABEL);
                    traces.add(trace);
                }
                //log.info("traces:" + traces);
                if (!CollectionUtils.isEmpty(traces)) {
                    this.saveBatch(traces);
                }
            }
        }
    }

    private Integer queryTraceList(String billcode) {
        LambdaQueryWrapper<OmsOrderTrace> traceQueryWrapper = new LambdaQueryWrapper<>();
        traceQueryWrapper.eq(OmsOrderTrace::getTraceNo, billcode);
        return this.count(traceQueryWrapper);
    }*/

}
